# -*- coding: utf-8 -*-
# @Time        :2025/8/22 16:13
# @Author      :文刀水寿
# @File        : tasks.py
# """
#  @Description :
# """
import logging
import threading
import time
from datetime import datetime

import schedule

from App.until import update_feishu_tables
from FS_RPA import settings

logger = logging.getLogger(__name__)


def start_scheduler():
    # 每6小时执行一次
    # schedule.every(6).hours.do(run_update_task)
    # 指定时间运行
    schedule.every().day.at(settings.START_TIME1).do(run_update_task)

    # 启动后台线程运行调度器
    def run_schedule():
        logger.info("定时任务调度器已启动")
        while True:
            current_time = datetime.now()
            formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
            logger.info(f"当前时间为--->>>：{formatted_time}--->>>任务开始时间： {settings.START_TIME1}--->>>")
            time.sleep(3)  # 每分钟检查3次
            schedule.run_pending()  # 检查并执行到期任务

    # 守护线程：主程序退出时自动结束
    scheduler_thread = threading.Thread(target=run_schedule, daemon=True)
    scheduler_thread.start()


def run_update_task():
    """任务执行函数"""
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    logger.info(f"===== 定时任务开始执行（{current_time}） =====")
    result = update_feishu_tables()
    if result["success"]:
        logger.info(f"===== 定时任务执行成功（{current_time}） =====")
    else:
        logger.error(f"===== 定时任务执行失败：{result['error']} =====")

# import schedule
# import time
# import threading
# import logging
# from datetime import datetime, timedelta
# from django.conf import settings
# from App.until import update_feishu_tables
#
# logger = logging.getLogger(__name__)
#
#
# def start_scheduler():
#     # 配置任务
#     job = schedule.every(6).hours.do(run_update_task)
#
#     # job = schedule.every(30).seconds.do(run_update_task)
#
#     # job = schedule.every().day.at(settings.START_TIME1).do(run_update_task)
#
#     def run_schedule():
#         logger.info("定时任务调度器已启动")
#         while True:
#             current_time = datetime.now()
#             formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
#
#             # 获取下次任务执行时间
#             next_run_time = None
#             for scheduled_job in schedule.jobs:
#                 if scheduled_job.job_func == job.job_func:
#                     next_run_time = scheduled_job.next_run
#
#             if next_run_time:
#                 # 计算剩余时间（下次执行时间 - 当前时间）
#                 time_remaining = next_run_time - current_time
#                 # 格式化剩余时间（天:时:分:秒）
#                 days = time_remaining.days
#                 hours, remainder = divmod(time_remaining.seconds, 3600)
#                 minutes, seconds = divmod(remainder, 60)
#                 remaining_str = f"{days}天{hours}时{minutes}分{seconds}秒"
#             else:
#                 remaining_str = "未知"
#
#             if hasattr(settings, 'START_TIME1'):
#                 logger.info(
#                     f"当前时间：{formatted_time} "
#                     f"| 任务计划时间：{settings.START_TIME1} "
#                     f"| 距离下次执行还有：{remaining_str}"
#                 )
#             else:
#                 logger.info(
#                     f"当前时间：{formatted_time} "
#                     f"| 距离下次执行还有：{remaining_str}"
#                 )
#
#             schedule.run_pending()  # 执行到期任务
#             time.sleep(3)  # 每3秒检查一次
#
#     # 启动守护线程
#     scheduler_thread = threading.Thread(target=run_schedule, daemon=True)
#     scheduler_thread.start()
#
#
# def run_update_task():
#     """任务执行函数"""
#     current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
#     logger.info(f"===== 定时任务开始执行（{current_time}） =====")
#     result = update_feishu_tables()
#     if result["success"]:
#         logger.info(f"===== 定时任务执行成功（{current_time}） =====")
#     else:
#         logger.error(f"===== 定时任务执行失败：{result['error']} =====")
